<template>
  <el-card shadow="never">
    <div id="callcenter-workbench-container"></div>
  </el-card>
</template>

<script>
// 详情见 https://help.aliyun.com/document_detail/63063.html
export default {
  beforeDestroy() {
    // 确保下次创建workbench的config是最新的（包括instanceId、事件监听处理器的this上下文）：
    // 如果已经存在一个实例，销毁后重新创建
    if (this.workbench) {
      let container = this.$el.querySelector('#callcenter-workbench-container');
      container.removeChild(container.firstChild);
      window._AgentBarSdk.DestroyPhoneSdk();
      window._AgentBarSdk = null;
    }

    this.$off();
  },
  methods: {
    async load({instanceId}) {
      if (!window.WorkbenchSdk) {
        // 依赖资源最新版本号
        const VERSION_SIP = '0.1.3';
        const VERSION_VOIP = '2.7.8';
        const VERSION_SDK = '1.0.3'

        // 加载样式
        await loadStyle(`//g.alicdn.com/acca/workbench-sdk/${VERSION_SDK}/main.min.css`);
        // 加载好样式之后，加载脚本
        await loadScripts([
          `https://g.alicdn.com/cloudcallcenter/SIPml/${VERSION_SIP}/SIPml-api.js`,
          `https://g.alicdn.com/cloudcallcenter-voip/agentbar-sdk/${VERSION_VOIP}/index.js`,
          `https://g.alicdn.com/acca/workbench-sdk/${VERSION_SDK}/workbenchSdk.min.js`
        ]);

        function loadStyle(href) {
          return new Promise((resolve, reject) => {
            let link = document.createElement('link');
            link.rel ='stylesheet';
            link.type = 'text/css';
            link.href = href;
            link.onload = () => {
              resolve();
            };
            document.head.appendChild(link);
          });
        }

        function loadScripts(srcs) {
          let success = null;
          return new Promise((resolve, reject) => {
            success = resolve;
            loadScript(0);
          });
          // 依次加载所有脚本
          function loadScript(loadedCount) {
            let script = document.createElement('script');
            script.src = srcs[loadedCount];
            script.onload = () => {
              if (loadedCount + 1 == srcs.length) {
                success();
              } else {
                loadScript(loadedCount + 1);
              }
            };
            document.head.appendChild(script);
          }
        }
      }
      
      // 依赖资源全部加载完成，初始化workbench
      this.init(instanceId);
      this.$emit('loadSuccess');
    },
    init(instanceId) {
      this.workbench = new window.WorkbenchSdk({
        dom: 'callcenter-workbench-container',
        instanceId: instanceId,
        ajaxPath: '/api/callcenter/workbench/api',
        ajaxMethod: 'post',
        header: true,
        enableRecord: true,
        onInit: () => {
          console.log('WorkbenchSdk 初始完成');
          this.workbench.register();
        },
        onErrorNotify(error) {
          this.$message.error(error.errorMsgTip);
          console.error(error);
        },
        onCallComing: (connid, callerNumber, calleeNumber, contacId) => {
          this.$emit('callComing', connid, callerNumber, calleeNumber, contacId);
        },
        onCallRelease: () => {
          this.$emit('callRelease');
        },
        onHangUp: () => {
          this.$emit('hangUp');
        }
      });
    }
  }
}
</script>

<style scoped>
#callcenter-workbench-container {
  margin-top: 4px;
}

>>> .el-card__body {
  padding: 0px 4px;
  min-height: 584px;
}
</style>